<?php
/**
 * $Id: PhotoDAL.class.php 1144 2008-08-19 08:10:12Z pawy $
 * Enter description here...
 *
 */
class PhotoDAL {

	const PHOTO_NEW_EXT = 'jpg';
	
	static private $params = array(
		'groups' => array(
			'ext' => 'jpg', 
			'params' => array(
				'box64' => array('x' => 64, 'y' => 64, 'background' => 'ffffff', 'fill' => true, 'position' => 'c', 'padding' => 0),
				'box40' => array('x' => 40, 'y' => 40, 'background' => 'ffffff', 'fill' => true, 'position' => 'c', 'padding' => 0),
				'box100' => array('x' => 100, 'y' => 100, 'background' => 'ffffff', 'fill' => true, 'position' => 'c', 'padding' => 0),
			)
		),
		
		'gallery_cropp_temporary' => array(
			'ext' => self::PHOTO_NEW_EXT,
			'params' => array(
				'temp' => array('x' => 300, 'y' => 300, 'background' => 'ffffff', 'fill' => true, 'position' => 'c', 'padding' => 0, 'resize' => true)	
			)
		),
		
		'gallery_crop' => array(
			'ext' => self::PHOTO_NEW_EXT,
			'params' => array(
				'70' => array('x' => 70, 'y' => 70, 'background' => 'ffffff', 'fill' => true, 'position' => 'c', 'padding' => 0, 'cropp' => true, 'resize' => true),
				'140' => array('x' => 140, 'y' => 140, 'background' => 'ffffff', 'fill' => true, 'position' => 'c', 'padding' => 0, 'cropp' => true, 'resize' => true),
				'750' => array('x' => 750, 'y' => 750, 'background' => 'ffffff', 'fill' => false, 'position' => 'c', 'padding' => 0, 'cropp' => false, 'resize' => false)
			)
		)
	);
	
	
	
	/**
	 * Przygotowuje nowy wiersz dla nowego zdj�cia
	 *
	 * @param int $modelId - identyfkator modelki
	 * @return Identyfikator nowego zdj�cia
	 */
	public static function Insert(Photo $photoObj, $wpisId) {
		$db = Registry::Get('db');
		$sql = "INSERT INTO wp_photo (id_wp_wpis, source)		
			 VALUES (:1, :2) ";
		
		$stmt = $db->prepare($sql)
		->bindParam(1, $wpisId)
		->bindParam(2, $photoObj->GetSource())			
		->execute();

		return $stmt->GetInsertionId();
	}
	
	
	
			
	/**
	 * Wysyla miniature
	 *
	 * @param Photo $objPhoto
	 * @param string $thumbType
	 * @param array $SourceFileArray
	 */
	public static function UploadThumb ($objPhoto, $thumbType, $SourceFileArray, $croppingOption="middle") {
		if (   is_uploaded_file($SourceFileArray["tmp_name"])   )	{
			$directory = PATH_STATIC."/image/".$objPhoto->GetClassName()."/".$objPhoto->GetId();
			PhotoDAL::mkdirs(  $directory  );
			

					
			//$DestinationFile = $objPhoto->GetPath() . $objPhoto->GetName();
			$DestinationFile = $directory."/".$objPhoto->GetClassName()."_".$objPhoto->GetId()."_".$thumbType.".jpg";
	
			if (file_exists($DestinationFile)){
				unlink($DestinationFile);
			}
			
			//TODO FILES Kopiowanie pliku 
			move_uploaded_file($SourceFileArray["tmp_name"], $DestinationFile);
			FilesOperation::SaveFile($DestinationFile, __METHOD__);
			
			
			// zaczynamy kwesti� generowania miniaturek ...
			$size = getimagesize($DestinationFile);
			
			switch ($thumbType) {
				
				default:
			
					$wspolczynnik_proporcji = 0.8;
					$wspolczynnik_zdjecia_uploadowanego = $size[0]/$size[1];			
					
					$imgsrc = new mImage($DestinationFile);
					if ($wspolczynnik_zdjecia_uploadowanego > $wspolczynnik_proporcji) {
					//zdj�cie szersze ni� porz�dane
						$poziom_wzgledem_pionu = $size[1] * $wspolczynnik_proporcji;
						
						switch ($croppingOption) {
							default: $marginesy = floor(   ($size[0] - $poziom_wzgledem_pionu)/2   ); break;
							case "topleft": $marginesy=0; break; 
							case "bottomright": $marginesy = floor(   ($size[0] - $poziom_wzgledem_pionu)   ); break;
						}
						
						$imgsrc->crop1($marginesy, 0, $poziom_wzgledem_pionu, $size[1]);
						
					} else {
					//zdj�cie w�sze ni� porz�dane
						$pion_wzgledem_poziomu = $size[0] * (1/$wspolczynnik_proporcji);
						$marginesy = floor(   ($size[1] - $pion_wzgledem_poziomu)/2   );
						
						switch ($croppingOption) {
							default: $marginesy = floor(   ($size[1] - $pion_wzgledem_poziomu)/2   ); break;
							case "topleft": $marginesy=0; break; 
							case "bottomright": $marginesy = floor(   ($size[1] - $pion_wzgledem_poziomu)   ); break;
						}
						
						$imgsrc->crop1(0, $marginesy, $size[0], $pion_wzgledem_poziomu);
					}

					$thumbWidth = $thumbType;
					
			break;
			
			case "sq":
					$wspolczynnik_proporcji = 1;
					$wspolczynnik_zdjecia_uploadowanego = $size[0]/$size[1];			
					
					$imgsrc = new mImage($DestinationFile);
					if ($wspolczynnik_zdjecia_uploadowanego > $wspolczynnik_proporcji) {
					//zdj�cie szersze ni� porz�dane
						$poziom_wzgledem_pionu = $size[1] * $wspolczynnik_proporcji;
						
						switch ($croppingOption) {
							default: $marginesy = floor(   ($size[0] - $poziom_wzgledem_pionu)/2   ); break;
							case "topleft": $marginesy=0; break; 
							case "bottomright": $marginesy = floor(   ($size[0] - $poziom_wzgledem_pionu)   ); break;
						}
						
						$imgsrc->crop1($marginesy, 0, $poziom_wzgledem_pionu, $size[1]);
						
					} else {
					//zdj�cie w�sze ni� porz�dane
						$pion_wzgledem_poziomu = $size[0] * (1/$wspolczynnik_proporcji);
						$marginesy = floor(   ($size[1] - $pion_wzgledem_poziomu)/2   );
						
						switch ($croppingOption) {
							default: $marginesy = floor(   ($size[1] - $pion_wzgledem_poziomu)/2   ); break;
							case "topleft": $marginesy=0; break; 
							case "bottomright": $marginesy = floor(   ($size[1] - $pion_wzgledem_poziomu)   ); break;
						}
						
						$imgsrc->crop1(0, $marginesy, $size[0], $pion_wzgledem_poziomu);
					}
					$thumbWidth = 80;
			break;
			}
			
			$imgsrc->saveToFile($DestinationFile , 'jpg', 90, true);
			//TODO FILES Kopiowanie pliku
			FilesOperation::SaveFile($DestinationFile, __METHOD__);
			unset ($imgsrc);
			
			
			/*
			if ($thumbType == "sq") {
				$thumbWidth = 80;
			} else {
				$thumbWidth = $thumbType;
			}
			*/
			$img = new mImage($DestinationFile);			
			$img->scaleProp($thumbWidth, $thumbWidth*2, 'ffffff', false, 'c', 0);
			/*
			if ($thumbType == "sq") {
				
				$img->crop1(0, 0, $thumbWidth, $thumbWidth);
			}
			*/
			
			$img->saveToFile($directory."/".$objPhoto->GetClassName()."_".$objPhoto->GetId()."_".$thumbType.".jpg", 'jpg', 90, true);
			//TODO FILES Kopiowanie pliku
			FilesOperation::SaveFile($directory."/".$objPhoto->GetClassName()."_".$objPhoto->GetId()."_".$thumbType.".jpg", __METHOD__);
			
			
		}
	}
	
	public static function FileDelete(DataObject $objPhoto) {

		$id = $objPhoto->GetId();
		$table = $objPhoto->GetTableName();
		
		FilesOperation::DeleteFileFromStorage($objPhoto -> GetPhoto());
		FilesOperation::DeleteFileFromStorage($objPhoto -> GetPhoto400());
		FilesOperation::DeleteFileFromStorage($objPhoto -> GetPhoto170());
		FilesOperation::DeleteFileFromStorage($objPhoto -> GetPhoto120());
		FilesOperation::DeleteFileFromStorage($objPhoto -> GetPhoto70());
		FilesOperation::DeleteFileFromStorage($objPhoto -> GetPhotoSq());
		
		$sql = "UPDATE " . $table . " SET photo = NULL, photo_400 = NULL, photo_170 = NULL, photo_120 = NULL, photo_70 = NULL, photo_sq = NULL WHERE id_" . $table ." = " . $id;
		
		Registry::Get('db') -> Prepare($sql) -> Execute();
		return true;
		
	}
	
	
	/**
	 * Wczytuje zdj�cie na serwer
	 *
	 * @param $_FILES $SourceFileArray - tablica uploadowanych plikow z formularza
	 * @param Photo $objPhoto - obiekt photo
	 * @param unknown_type $CropMargin - g�rny margines kadrowania miniaturki kwadratowej
	 * @return true/false
	 */
	public static function FileUpload($SourceFileArray,DataObject $objPhoto, $croppingOption, $CropAllow=false) {
		//$source=$arrfile['tmp_name'];
		
		if (  is_uploaded_file($SourceFileArray["tmp_name"]) || is_file($SourceFileArray["tmp_name"])){

			FilesOperation::DeleteFileFromStorage($objPhoto -> GetPhoto());
			FilesOperation::DeleteFileFromStorage($objPhoto -> GetPhoto400());
			FilesOperation::DeleteFileFromStorage($objPhoto -> GetPhoto170());
			FilesOperation::DeleteFileFromStorage($objPhoto -> GetPhoto120());
			FilesOperation::DeleteFileFromStorage($objPhoto -> GetPhoto70());
			FilesOperation::DeleteFileFromStorage($objPhoto -> GetPhotoSq());
			
		
			if(STORAGE_TYPE == ST_TYPE_LOCAL) {
				$directory = PATH_STATIC . DIRECTORY_SEPARATOR . "upload" . DIRECTORY_SEPARATOR . "image" . DIRECTORY_SEPARATOR .$objPhoto->GetClassName(). DIRECTORY_SEPARATOR . $objPhoto->GetId();
			} else {
				$tempDir = explode(DIRECTORY_SEPARATOR, dirname(__FILE__));
				array_pop($tempDir);
				$directory = implode(DIRECTORY_SEPARATOR, $tempDir) . DIRECTORY_SEPARATOR . 'temp' . DIRECTORY_SEPARATOR . 'fileUpload' . DIRECTORY_SEPARATOR;
			}
			
			switch ($SourceFileArray['type']){
				default: 
					if (file_exists($SourceFileArray["tmp_name"])){
						unlink($SourceFileArray["tmp_name"]);
					}
					return false;
				break;
				case 'image/gif': $format = 'gif'; 
				break; 
				case 'image/jpeg':
				case 'image/pjpeg':
					$format = 'jpg';
				break;
				case 'image/png':
				case 'image/x-png':
					$format = 'jpg';
				break; 
                  }

			$newphoto = substr(md5(microtime()), 0, 5).'.'.$format;
			
			$id = $objPhoto->GetId();
			$table = $objPhoto->GetTableName();
			
			if(STORAGE_TYPE == ST_TYPE_LOCAL) {
				$photoPathPart = $directory . DIRECTORY_SEPARATOR . $objPhoto->GetClassName()."_".$objPhoto->GetId();
			} else {
				$photoPathPart = $directory . $objPhoto->GetClassName()."_".$objPhoto->GetId();
			}
			
			
			$photo = $objPhoto->GetPhoto();
			if($photo){ 
				self::delete($objPhoto);
			}
			
			PhotoDAL::mkdirs(  $directory  );
			
							
			//$DestinationFile = $objPhoto->GetPath() . $objPhoto->GetName();
			$DestinationFile = $photoPathPart . $newphoto;

//			if (file_exists($DestinationFile)){
//				unlink($DestinationFile);
//			}
			
			//zmieniono move_uploaded_file na rename dla celow zipa
			//move_uploaded_file($SourceFileArray["tmp_name"], $DestinationFile);
			
			$add = array();
			
			//TODO FILES Kopiowanie pliku 
			rename($SourceFileArray["tmp_name"], $DestinationFile);
//			FilesOperation::SaveFile($DestinationFile, __METHOD__);
			$add['photo'] =  FilesOperation::UploadFileToStorage($DestinationFile, __METHOD__);
			
			
			
			$size = getimagesize($DestinationFile);
			

// oryginalne zdj�cie (nie kadrowane do proporcji ... mog� wgra� co si� tylko podoba			
			$img_oryginal = new mImage($DestinationFile);			
			$img_oryginal->scaleProp(400, 400*2, 'ffffff', false, 'c', 0);
			$img_oryginal->saveToFile($photoPathPart . "_400_".$newphoto, $format, 90, true);
//			FilesOperation::SaveFile($photoPathPart . "_400_".$newphoto, __METHOD__);
			$add['photo_400'] = FilesOperation::UploadFileToStorage($photoPathPart . "_400_".$newphoto, __METHOD__);
			
			//TODO FILES Kopiowanie pliku

// ---- miniaturki proporcji 8:10
			$wspolczynnik_proporcji = 0.8;
			$wspolczynnik_zdjecia_uploadowanego = $size[0]/$size[1];			
			
			$img8_10 = new mImage($DestinationFile);
			if ($wspolczynnik_zdjecia_uploadowanego > $wspolczynnik_proporcji) {			
				$poziom_wzgledem_pionu = $size[1] * $wspolczynnik_proporcji;				
				switch ($croppingOption) {
					default: $marginesy = floor(   ($size[0] - $poziom_wzgledem_pionu)/2   ); break;
					case "topleft": $marginesy=0; break; 
					case "bottomright": $marginesy = floor(   ($size[0] - $poziom_wzgledem_pionu)   ); break;
				}						
				
				$img8_10->crop1($marginesy, 0, $poziom_wzgledem_pionu, $size[1]);
			} else {			
				$pion_wzgledem_poziomu = $size[0] * (1/$wspolczynnik_proporcji);				
				switch ($croppingOption) {
					default: $marginesy = floor(   ($size[1] - $pion_wzgledem_poziomu)/2   ); break;
					case "topleft": $marginesy=0; break; 
					case "bottomright": $marginesy = floor(   ($size[1] - $pion_wzgledem_poziomu)   ); break;
				}
						
				$img8_10->crop1(0, $marginesy, $size[0], $pion_wzgledem_poziomu);
			}
			
					
			// miniaturka 170			
			$img8_10->scaleProp(170, 170*2, 'ffffff', false, 'c', 0);			
			$img8_10->saveToFile($photoPathPart . "_170_".$newphoto, $format, 90, true);
			//TODO FILES Kopiowanie pliku
//			FilesOperation::SaveFile($photoPathPart . "_170_".$newphoto, __METHOD__);
			$add['photo_170'] = FilesOperation::UploadFileToStorage($photoPathPart . "_170_".$newphoto, __METHOD__);
			
			
			// miniaturka 120			
			$img8_10->scaleProp(120, 120*2, 'ffffff', false, 'c', 0);
			$img8_10->saveToFile($directory.$objPhoto->GetClassName()."_".$objPhoto->GetId()."_120_".$newphoto, $format, 90, true);
			//TODO FILES Kopiowanie pliku
//			FilesOperation::SaveFile($photoPathPart . "_120_".$newphoto, __METHOD__);
			$add['photo_120'] = FilesOperation::UploadFileToStorage($photoPathPart . "_120_".$newphoto, __METHOD__);
			
			
			
			// miniaturka 70
			$img8_10->scaleProp(70, 70*2, 'ffffff', false, 'c', 0);
			$img8_10->saveToFile($photoPathPart . "_70_".$newphoto, $format, 90, true);
			//TODO FILES Kopiowanie pliku
//			FilesOperation::SaveFile($photoPathPart . "_70_".$newphoto, __METHOD__);
			$add['photo_70'] = FilesOperation::UploadFileToStorage($photoPathPart . "_70_".$newphoto, __METHOD__);
			
			

// ---- miniaturka kwadratowa
			// miniaturka Sq
					$wspolczynnik_proporcji = 1;
					$wspolczynnik_zdjecia_uploadowanego = $size[0]/$size[1];			
					
					$imgsq = new mImage($DestinationFile);
					if ($wspolczynnik_zdjecia_uploadowanego > $wspolczynnik_proporcji) {
						$poziom_wzgledem_pionu = $size[1] * $wspolczynnik_proporcji;
						
						switch ($croppingOption) {
							default: $marginesy = floor(   ($size[0] - $poziom_wzgledem_pionu)/2   ); break;
							case "topleft": $marginesy=0; break; 
							case "bottomright": $marginesy = floor(   ($size[0] - $poziom_wzgledem_pionu)   ); break;
						}
						
						$imgsq->crop1($marginesy, 0, $poziom_wzgledem_pionu, $size[1]);
						
					} else {
						$pion_wzgledem_poziomu = $size[0] * (1/$wspolczynnik_proporcji);
						$marginesy = floor(   ($size[1] - $pion_wzgledem_poziomu)/2   );
						
						switch ($croppingOption) {
							default: $marginesy = floor(   ($size[1] - $pion_wzgledem_poziomu)/2   ); break;
							case "topleft": $marginesy=0; break; 
							case "bottomright": $marginesy = floor(   ($size[1] - $pion_wzgledem_poziomu)   ); break;
						}
						
						$imgsq->crop1(0, $marginesy, $size[0], $pion_wzgledem_poziomu);
					}
					

			$imgsq->scaleProp(80, 80*2, 'ffffff', false, 'c', 0);
			$imgsq->saveToFile($photoPathPart . "_sq_".$newphoto, $format, 90, true);
			//TODO FILES Kopiowanie pliku
//			FilesOperation::SaveFile($photoPathPart . "_sq_".$newphoto, __METHOD__);
			$add['photo_sq'] = FilesOperation::UploadFileToStorage($photoPathPart . "_sq_".$newphoto, __METHOD__);
			
			if(STORAGE_TYPE == ST_TYPE_SERVER) {
				unlink($DestinationFile);
				unlink($photoPathPart . "_400_".$newphoto);
				unlink($photoPathPart . "_170_".$newphoto);
				unlink($photoPathPart . "_120_".$newphoto);
				unlink($photoPathPart . "_70_".$newphoto);
				unlink($photoPathPart . "_sq_".$newphoto);
			}

			$first = true;			
			$sql = "UPDATE " . $table ." SET " ;
			foreach($add as $k => $v) {
				if(false != $v) {
					$sql .=  ((true == $first)?"":", ") . "" . $k ." = '" . $v . "'";
					$first = false;
				} else {
					unset($add[$k]);
				}
			}
			
			if(empty($add)) {
				return false;
			}
			
			$sql .= " WHERE id_" . $table ." = '" . $id . "' LIMIT 1;";
			
			Registry::Get('db') -> Prepare($sql) -> Execute();
			
			return true;
			
//			$objPhoto->SetPhoto($newphoto);
//			$db = Registry::Get('db');
//			$sql = 'UPDATE '.$table.' SET photo = \''.$newphoto.'\' WHERE id_'.$table.' = '.$id.'
//			 LIMIT 1';
//			
//			$stmt = $db->prepare($sql)->execute();
//							
//			return true;
		}
		else {
			return false;
		}
	}

	/**
	 * Metoda tworzy katalogi
	 *
	 * @param string $dir sciezka katalog�w
	 * @param int $mode prawa zapisu
	 * @param bool $recursive czy ma tworzy� katalogi rekursywnie
	 * @return bool
	 */
	public static function mkdirs($dir, $mode = 0777, $recursive = true) {
	  if( is_null($dir) || $dir === "" ){
	   return FALSE;
	  }
	  if( is_dir($dir) || $dir === DIRECTORY_SEPARATOR ){
	   return TRUE;
	  }
	  if( PhotoDAL::mkdirs(dirname($dir), $mode, $recursive) ){
	   return mkdir($dir, $mode);
	  }
	  return FALSE;
	}
		
	
	
	
	/**
	 * Usuwa zdj�cie z bazy
	 *
	 * @param unknown_type $objPhoto
	 * @param unknown_type $modelType
	 */
	public function delete (DataObject $objPhoto) {

		$photo = $objPhoto->GetPhoto();
		if($photo){
			$id = $objPhoto->GetId();
			$table = $objPhoto->GetTableName();

			$db = Registry::Get('db');
			$sql = 'UPDATE '.$table.' SET photo = NULL WHERE id_'.$table.' = '.$id.'
			 LIMIT 1';
			
			$stmt = $db->prepare($sql)->execute();

			$directory = PATH_STATIC."/image/".$objPhoto->GetClassName()."/".$objPhoto->GetId();

			$DestinationFile = $directory."/".$objPhoto->GetClassName()."_".$objPhoto->GetId()."_$photo";
			$DestinationFile400 = $directory."/".$objPhoto->GetClassName()."_".$objPhoto->GetId()."_400_$photo";
			$DestinationFile170 = $directory."/".$objPhoto->GetClassName()."_".$objPhoto->GetId()."_170_$photo";
			$DestinationFile120 = $directory."/".$objPhoto->GetClassName()."_".$objPhoto->GetId()."_120_$photo";
			$DestinationFile70 = $directory."/".$objPhoto->GetClassName()."_".$objPhoto->GetId()."_70_$photo";
			$DestinationFileSq = $directory."/".$objPhoto->GetClassName()."_".$objPhoto->GetId()."_sq_$photo";



			if (file_exists($DestinationFile)) { 
				unlink($DestinationFile); 
				//TODO FILES usuwanie pliku
				FilesOperation::DeleteFile($DestinationFile, __METHOD__);
			}
			if (file_exists($DestinationFile400)) { 
				unlink($DestinationFile400); 
				//TODO FILES usuwanie pliku
				FilesOperation::DeleteFile($DestinationFile400, __METHOD__);
			}
			if (file_exists($DestinationFile170)) { 
				unlink($DestinationFile170); 
				//TODO FILES usuwanie pliku
				FilesOperation::DeleteFile($DestinationFile170, __METHOD__);
			}
			if (file_exists($DestinationFile120)) { 
				unlink($DestinationFile120); 
				//TODO FILES usuwanie pliku
				FilesOperation::DeleteFile($DestinationFile120, __METHOD__);
			}
			if (file_exists($DestinationFile70))  { 
				unlink($DestinationFile70); 
				//TODO FILES usuwanie pliku
				FilesOperation::DeleteFile($DestinationFile70, __METHOD__);
			}
			if (file_exists($DestinationFileSq))  { 
				unlink($DestinationFileSq); 
				//TODO FILES usuwanie pliku
				FilesOperation::DeleteFile($DestinationFileSq, __METHOD__);
			}

			if (file_exists($directory)) { 
				rmdir($directory); 
				//TODO FILES usuwanie directory
				FilesOperation::DeleteDirectory($directory, __METHOD__);
			}
		}
		
	}
	
	
	

	
	/**
	 * Dodaje tablic� zdj��
	 *
	 * @param array $sourceFileArray
	 * @param int Wpis ID
	 */
	public function PhotoUpload($sourceFileArray, $wpisId) {
		$imgSort = 0;
		foreach($sourceFileArray['name'] as $key => $value) {
			$name = $imgSort . ".";
			$directory = PATH_STATIC . "/upload/Strona/Wpis/" . $wpisId;
			
			PhotoDAL::mkdirs($directory);
			
			if(file_exists($directory . "/" . $name)) {
				unlink($directory . "/" . $name);
			}
			$type = explode("/", $sourceFileArray['type'][$key]);
			if($type[1] == "jpeg") $type[1] = "jpg";
			move_uploaded_file($sourceFileArray['tmp_name'][$key], $directory . "/" . $name . $type[1]);
			$obj = new Photo(-1, $wpisId);
			$obj->SetSource($imgSort.".".$type[1]);
			PhotoDAL::Insert($obj, $wpisId);
			$imgSort++;
		}
	}

	public static function SimpleDelete($photoName,$localStorage = false)
	{
		if(is_array($photoName) && isset($photoName[1]))
		{
			$directory = PATH_STATIC_CONTENT . "/upload" . DIRECTORY_SEPARATOR . "image" . DIRECTORY_SEPARATOR . $photoName[0];
			$destinationFile = $directory . DIRECTORY_SEPARATOR . $photoName[1];
			if(STORAGE_TYPE == ST_TYPE_LOCAL || $localStorage == true)
				unlink($destinationFile);
				
			FilesOperation::DeleteFileFromStorage($photoName[1],$localStorage);
		}
		else if (!is_array($photoName))
		{
			FilesOperation::DeleteFileFromStorage($photoName,$localStorage);
		}
	}
	/**
	 * Wczytuje zdj�cie na serwer
	 *
	 * @param $_FILES $SourceFileArray - tablica uploadowanych plikow z formularza
	 * @param Photo $objPhoto - obiekt photo
	 * @param unknown_type $CropMargin - g�rny margines kadrowania miniaturki kwadratowej
	 * @return true/false
	 */
	public static function SimpleFileUpload($SourceFileArray,$photoName,$photoSize, $croppingOption = null, $CropAllow=false,$localStorage = false) {
		//$source=$arrfile['tmp_name'];

//		$logger = LoggerManager::getLogger(__CLASS__);
//		$logger -> debug('FileUpload: run...');
//		$logger -> debug('FileUpload: $sourceFileArray: ' . serialize($SourceFileArray));
		if (is_uploaded_file($SourceFileArray["tmp_name"]) || is_file($SourceFileArray["tmp_name"]))
		{

			if(STORAGE_TYPE == ST_TYPE_LOCAL || $localStorage == true)
			{
				$directory = PATH_STATIC_CONTENT  . "/upload" . DIRECTORY_SEPARATOR . "image" . DIRECTORY_SEPARATOR . $photoName[0];
			}
			else
			{
				$tempDir = explode(DIRECTORY_SEPARATOR, dirname(__FILE__));
				array_pop($tempDir);
				$directory = implode(DIRECTORY_SEPARATOR, $tempDir) . DIRECTORY_SEPARATOR . 'temp' . DIRECTORY_SEPARATOR .  'fileupload' . DIRECTORY_SEPARATOR . $photoName[0];
			}
			switch ($SourceFileArray['type']){
				default:
					if (file_exists($SourceFileArray["tmp_name"])){
						unlink($SourceFileArray["tmp_name"]);
					}
					return 1;
				break;
				case 'image/gif': $format = 'gif';
				break;
				case 'image/jpeg':
				case 'image/pjpeg':
					$format = 'jpg';
				break;
				case 'image/png':
				case 'image/x-png':
					$format = 'jpg';
				break;
                  }

			PhotoDAL::mkdirs(  $directory  );

			$DestinationFile = $directory . DIRECTORY_SEPARATOR . $photoName[1] ."." .$format;

			//zmieniono move_uploaded_file na rename dla celow zipa
			//move_uploaded_file($SourceFileArray["tmp_name"], $DestinationFile);

			$filename = '';

			copy($SourceFileArray["tmp_name"], $DestinationFile);

			$size = getimagesize($DestinationFile);

			if ($size[0] == $photoSize[0] && $size[1] == $photoSize[1]) {
				$filename = FilesOperation::UploadFileToStorage($DestinationFile, __METHOD__,false,$localStorage);

				return $filename;
			} else {

				// sprawdzamy czy nie skalujemy do wiekszych rozmiarow
				$wspolczynnik_proporcji = $photoSize[0]/$photoSize[1];

				// zapis zdj�cia
				if($photoSize[0] == $photoSize[1])
				{
					// ---- miniaturka kwadratowa
					// miniaturka Sq
					$wspolczynnik_proporcji = 1;
					$wspolczynnik_zdjecia_uploadowanego = $size[0]/$size[1];

					$imgsq = new mImage($DestinationFile);
					if($size[0] > $photoSize[0] || $size[1] > $photoSize[1]){
						if ($wspolczynnik_zdjecia_uploadowanego > $wspolczynnik_proporcji) {
							$poziom_wzgledem_pionu = $size[1] * $wspolczynnik_proporcji;
	
							switch ($croppingOption) {
								default: $marginesy = ceil(   ($size[0] - $poziom_wzgledem_pionu)/2   ); break;
								case "topleft": $marginesy=0; break;
								case "bottomright": $marginesy = ceil(   ($size[0] - $poziom_wzgledem_pionu)   ); break;
							}
	
							$imgsq->crop1($marginesy, 0, $poziom_wzgledem_pionu, $size[1]);
	
						} else {
							$pion_wzgledem_poziomu = $size[0] * (1/$wspolczynnik_proporcji);
							$marginesy = ceil(   ($size[1] - $pion_wzgledem_poziomu)/2   );
	
							switch ($croppingOption) {
								default: $marginesy = ceil(   ($size[1] - $pion_wzgledem_poziomu)/2   ); break;
								case "topleft": $marginesy=0; break;
								case "bottomright": $marginesy = ceil(   ($size[1] - $pion_wzgledem_poziomu)   ); break;
							}
	
							$imgsq->crop1(0, $marginesy, $size[0], $pion_wzgledem_poziomu);
						}
	
						$imgsq->scaleProp($photoSize[0], $photoSize[1], 'ffffff', false, 'c', 0);
					}
					$imgsq->saveToFile($DestinationFile, $format, 90, true);
					$filename = FilesOperation::UploadFileToStorage($DestinationFile, __METHOD__,false,$localStorage);
				}
				else
				{
					// ---- miniaturki proporcji 8:10
					
					//MAGO - nie wiem po co tutaj ten local storage - ale mi się miniatury nie robią jak to tu jest
//					if($localStorage == false)
//					{
					$img8_10 = new mImage($DestinationFile);
						if($size[0] > $photoSize[0] || $size[1] > $photoSize[1]){
							$wspolczynnik_zdjecia_uploadowanego = $size[0]/$size[1];
	
							
							if ($wspolczynnik_zdjecia_uploadowanego > $wspolczynnik_proporcji) {
								$poziom_wzgledem_pionu = $size[1] * $wspolczynnik_proporcji;
								switch ($croppingOption) {
									default: $marginesy = ceil(   ($size[0] - $poziom_wzgledem_pionu)/2   ); break;
									case "topleft": $marginesy=0; break;
									case "bottomright": $marginesy = ceil(   ($size[0] - $poziom_wzgledem_pionu)   ); break;
								}
								if($CropAllow == true)
									$img8_10->crop1($marginesy, 0, $poziom_wzgledem_pionu, $size[1]);
							} else {
								$pion_wzgledem_poziomu = $size[0] * (1/$wspolczynnik_proporcji);
								switch ($croppingOption) {
									default: $marginesy = ceil(   ($size[1] - $pion_wzgledem_poziomu)/2   ); break;
									case "topleft": $marginesy=0; break;
									case "bottomright": $marginesy = ceil(   ($size[1] - $pion_wzgledem_poziomu)   ); break;
								}
								if($CropAllow == true)
									$img8_10->crop1(0, $marginesy, $size[0], $pion_wzgledem_poziomu);
							}
	
							$img8_10->scaleProp($photoSize[0], $photoSize[1], 'ffffff', false, 'c', 0);
						}
						$img8_10->saveToFile($DestinationFile, $format, 90, true);
//					}
					$filename = FilesOperation::UploadFileToStorage($DestinationFile, __METHOD__,false,$localStorage);
				}
				if(STORAGE_TYPE == ST_TYPE_SERVER && $localStorage == false)
				{
					unlink($DestinationFile);
					//unlink($photoPathPart . [1]);
				}
				return $filename;
			}
		}
		else {
			return false;
		}
	}


	/**
	 * Przenosi tymczasowo zapisane zdjęcie do zdjęć zapisanych na stałe,
	 * przy okazji obcinając je wedle wskazań croppera, i resizując do
	 * docelowego rozmiaru.
	 *
	 * @param string $fileName
	 * @param int $x
	 * @param int $y
	 * @param int $width
	 * @param int $height
	 * @param int $destWidth
	 * @param int $destHeight
	 */
	public static function SaveTempFile($fileName, $destFile, $destDir, $x, $y, $width, $height, $destSmallSize, $destSize, $destBigSize) {
		$file = PATH_STATIC_CONTENT . DIRECTORY_SEPARATOR . $fileName;

		$destDir = PATH_STATIC_CONTENT . DIRECTORY_SEPARATOR . $destDir;

		PhotoDAL::mkdirs($destDir);

		$destFileN = $destFile;
		$destFile = $destDir . DIRECTORY_SEPARATOR . $destFile;

		$image120 = new mImage($file);
		$image120->crop1($x, $y, $width, $height);
		$image120->scaleProp($destBigSize, $destBigSize, 'ffffff', false, 'c', 0);
		$image120->saveToFile($destFile . "120.jpg", 'jpg', 90, true);

		$image70 = new mImage($file);
		$image70->crop1($x, $y, $width, $height);
		$image70->scaleProp($destSize, $destSize, 'ffffff', false, 'c', 0);
		$image70->saveToFile($destFile . "70.jpg", 'jpg', 90, true);

		$image50 = new mImage($file);
		$image50->crop1($x, $y, $width, $height);
		$image50->scaleProp($destSmallSize, $destSmallSize, 'ffffff', false, 'c', 0);
		$image50->saveToFile($destFile . "50.jpg", 'jpg', 90, true);

		return $destFileN;
	}

	public function MoveFile($sourceFile, $destFile) {
		//echo("source = '$sourceFile'");
		//echo("dest = '$destFile'");
		//echo("dirtomake = '" . pathinfo($destFile, PATHINFO_DIRNAME) . "'");

		self::mkdirs(pathinfo($destFile, PATHINFO_DIRNAME));

		$size = array(50, 70, 120);

		foreach ($size as $s) {
			rename($sourceFile . $s . '.jpg', $destFile . $s . '.jpg');
		}
	}
    
	public function ExtSimplePhotoUpload($sourceFileArray, $path, $paramsArrayName = null, $newName = null, $returnName = null, $cropp = array()) {
    	// sciezka do galerii
    	
    	$dir = PATH_STATIC_CONTENT . DIRECTORY_SEPARATOR . $path;
    	PhotoDAL::mkdirs($dir);
    	// format
    	$newExt = null;
    	$ext = explode('.', $sourceFileArray['name']);
    	if(!empty($paramsArrayName) && isset(self::$params[$paramsArrayName]['ext'])) {
    		$newExt = self::$params[$paramsArrayName]['ext'];
    	} else {
    		$newExt = $ext[1];	
    	}
    	if(!in_array($newExt, array('jpg', 'jpeg', 'gif', 'png'))) {
    		return false;
    	}
    	// nazwa
    	$nName = null;
    	if(!empty($newName) && is_string($newName)) {
    		$nName = $newName;
    	} else {
    		$nName = $ext[0];
    	}
    	$fileDirName = $dir . DIRECTORY_SEPARATOR . $nName;
    	$newOrgFile = $fileDirName . '.' . $newExt;
    	// kopiowanie pliku
    	if(file_exists($newOrgFile)) {
    		unlink($newOrgFile);
    	}
    	// oryginal
    	if($newExt == $ext[0]) {
    		move_uploaded_file($sourceFileArray['tmp_name'], $newOrgFile);
    	} else {
    		$orgFile = new mImage($sourceFileArray['tmp_name']);
    		$orgFile->saveToFile($newOrgFile, $newExt, 90, true);
    	}
    	// mniejsze
    	if(!empty($paramsArrayName)) {
    		if(isset(self::$params[$paramsArrayName]['params'])) {
    			$paramsArray = self::$params[$paramsArrayName]['params'];
	    		foreach($paramsArray as $key => $v) {
	    			if(!empty($returnName) && $returnName == $key) {
	    				$nName = $nName . '_' . $key;
	    			}
	    			$nFile = new mImage($newOrgFile);
	    			if(!empty($cropp) && $v['cropp'] == true) {
	    				$nFile -> crop1($cropp['x'], $cropp['y'], $cropp['w'], $cropp['h']);
	    			}
	    			if($v['resize'] == true) {
	    				$nFile -> scaleProp($v['x'], $v['y'], $v['background'], $v['fill'], $v['position'], $v['padding']);
	    			} else {
	    				$size = getimagesize($newOrgFile);
	    				if($size[0] > $v['x'] || $size[1] > $v['y']) {
	    					$nFile -> scaleProp($v['x'], $v['y'], $v['background'], $v['fill'], $v['position'], $v['padding']);
	    				}
	    			}
	    			$nFile -> saveToFile($fileDirName . '_' . $key . '.' . $newExt, $newExt, 90, true);
	    		}
    		}
    	}
    	return $nName . '.' . $newExt;
	}
	
    public static function SimplePhotoUpload($sourceFileArray, $path, $dimnsionX=null, $dimensionY=null, $quality = 90) {
			
			$directory = PATH_STATIC_CONTENT . $path;
			$url = $path;

			PhotoDAL::mkdirs($directory);

			if(file_exists($directory . DS . $sourceFileArray['name'])) {
				unlink($directory . DS . $sourceFileArray['name']);
			}

			$destinationFilePath = $directory . DS . $sourceFileArray['name'];
			$destinationFileUrl = $url . URL_DELIMITER . $sourceFileArray['name'];
			
			move_uploaded_file($sourceFileArray['tmp_name'], $destinationFilePath);

            if($dimensionY!=null && $dimnsionX!=null) {
                $size = getimagesize($destinationFilePath);
			
			$imgOryginal = new mImage($destinationFilePath);
			$imgOryginal->scaleProp($dimnsionX, $dimensionY, 'ffffff', false, 'c', 0);
			$imgOryginal->saveToFile($destinationFilePath, 'jpg', $quality, true);
            }

			if (file_exists($destinationFilePath)) {
				return $destinationFileUrl;
			} else {
				return false;
			}

			//PhotoDAL::Insert($obj, $wpisId);

    }	
    
	/**
	 * Pusty konstruktor
	 *
	 */
	public function __construct() {
		
	}
}
?>